import React, {Component} from 'react';
import {ActivityIndicator, ListView, RefreshControl, Text, TouchableOpacity, View} from 'react-native';

import {SelStateMobAction} from '../../actions/resume_c'; //加载action
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import Cmanageres_list from './cmanageres_list';
import {SwipeListView} from 'react-native-swipe-list-view';
import {Cmanageres_Style as styles} from '../../../styles';
import {fetchRequest} from "../../util/fetch";
import {myAlert} from "../../util/compatible";

const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});//listView 数据判断方式
class Cmanageres_body extends Component {
    // 初始化模拟数据
    constructor(props) {
        super(props);
        this.state = {
            uploading: true, //下拉刷新按钮状态 (初始化加载时处在loading状态)
            dwloading: false, //上拉刷新按钮状态
            List: []
        };
        this.isFirst = true                         //页面第一次加载
    }

    //加载后渲染页面
    componentDidMount() {
        const {actions} = this.props;
        actions.SelStateMobAction({page: 1}); //初始化查询
    }

    render() {
        //获取用户列表数据及是否等待状态
        const {List} = this.props.postionSends.data;
        this.state.List = List;
        //创建listView数据源
        let dataSource = [];
        if (List === undefined) {
            dataSource = ds.cloneWithRows([]);
        } else {
            dataSource = ds.cloneWithRows(this.state.List);
        }
        return (
            <View style={{flex: 1}}>
                {/* <ListView
                    refreshControl={                            //是否更新
                        <RefreshControl                         //刷新控件
                            refreshing={this.state.uploading && this.props.postionSends.isloading}                  //刷新时候的小控件
                            onRefresh={this._onRefresh.bind(this)}
                        />}
                    enableEmptySections={true}
                    dataSource={dataSource}         //数据源(数组)
                    renderRow={this.renderRow.bind(this)}                 // 遍历数组的回调函数
                    onEndReachedThreshold={1}                  //滚动临界值（到达后执行onEndReached）
                    onEndReached={this.onEndReached.bind(this)}          //屏幕到底部的触发的事件
                    renderFooter={this.renderFooter.bind(this)}           //底部刷新组件
                /> */}

                <SwipeListView
                    refreshControl={                            //是否更新
                        <RefreshControl                         //刷新控件
                            refreshing={this.state.uploading && this.props.postionSends.isloading}                  //刷新时候的小控件
                            onRefresh={this._onRefresh.bind(this)}
                        />}
                    enableEmptySections={true}
                    dataSource={dataSource}         //数据源(数组)
                    renderRow={this.renderRow.bind(this)}                 // 遍历数组的回调函数
                    onEndReachedThreshold={1}                  //滚动临界值（到达后执行onEndReached）
                    onEndReached={this.onEndReached.bind(this)}          //屏幕到底部的触发的事件
                    renderFooter={this.renderFooter.bind(this)}
                    renderHiddenRow={(data, secId, rowId, rowMap) => (
                        <TouchableOpacity style={styles.cma_list}
                                          onPress={() => {
                                              this.delete(data.sendId);
                                              rowMap[`${secId}${rowId}`].closeRow();
                                          }}
                                          activeOpacity={1}>
                            <Text style={styles.cma_txt}>删除</Text>
                        </TouchableOpacity>
                    )}
                    rightOpenValue={-50}
                    disableRightSwipe={true}
                    closeOnRowPress={true}
                />

            </View>
        );
    }

    delete(sendId) {
        fetchRequest('PostionSend/deleteBySendId.go', 'POST', {sendId: sendId}).then(ret => {
            if (ret.msg === 'ok') {
                this._deleteRow(sendId)
            } else {
                myAlert('删除失败');
            }
        })
    }

    _deleteRow(id) {
        let count;
        let list = this.state.List;
        for (let i = 0; i < list.length; i++) {
            if (list[i].sendId === id) {
                count = i;
            }
        }
        this.state.List.splice(count, 1);
        this.setState({List: this.state.List});
    }

    //刷新隐藏按钮
    componentDidUpdate() {
        if (this.state.uploading && !this.props.postionSends.isloading) {
            this.setState({
                uploading: false //下拉刷新按钮状态：隐藏
            })
        }
        if (this.state.dwloading && !this.props.postionSends.isloading) {
            this.setState({
                dwloading: false //上拉刷新按钮状态：隐藏
            })
        }
    }

    //下拉刷新开始
    _onRefresh() {
        this.props.postionSends.isloading = true; //设置为加载状态
        const {actions} = this.props;
        actions.SelStateMobAction({page: 1});
        this.setState({
            uploading: true //下拉刷新按钮状态：显示
        });
    }

    onEndReached() {
        if (!this.isFirst && !this.props.postionSends.isloading) {
            const {page, pages} = this.props.postionSends.data;
            if (page !== pages) {//不等于最后一页加载
                const {actions} = this.props;
                actions.SelStateMobAction({page: page + 1});
                this.props.postionSends.isloading = true;
                this.setState({
                    dwloading: true //下拉刷新按钮状态 显示
                })
            }
        } else {
            this.isFirst = false;
        }
    }

    renderFooter() {
        if (!this.props.postionSends.ret) {
            //console.log("请求失败");
        }
        if (this.state.dwloading) {
            return (<View style={{marginVertical: 10}}>
                <ActivityIndicator
                    animating={true}
                    style={{height: 10, alignItems: 'center', justifyContent: 'center', padding: 1,}}
                    size="small"/>
            </View>);
        }
        if (this.state.uploading) {
            return (<View style={{marginVertical: 10, height: 100, alignItems: 'center', justifyContent: 'flex-end'}}>
                <Text>玩命加载ing</Text>
            </View>);
        }
        return (<View style={{marginVertical: 10}}/>);
    }

    renderRow(rowData) {
        return (
            <View>
                <Cmanageres_list
                    postionSend={rowData}
                    resume={rowData.resumes}
                    navigation={this.props.navigation}/>
            </View>
        )
    }
}

//组合action
let actions = {
    SelStateMobAction,
};
//连接state到props
const mapStateToProps = state => {
    return {
        postionSends: state.SelStateMobReducer             //自己的reducers
    }
};
//连接action
const mapDispatchToProps = (dispatch) => {
    return {
        actions: bindActionCreators(actions, dispatch)
    }
};
//导出组合好的组件(组合后状态改变重新渲染组合组件的页面)
export default connect(
    mapStateToProps, mapDispatchToProps
)(Cmanageres_body);